# -*- coding:utf-8 -*-

# @Time    : 2023/7/30 21:07
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #


import asyncio
import copy
import json
import math
import re
import traceback

from nltk import deprecated

from bot.insurance_planner_gpt.agent.product_organize.premium_calculation_cn import premium_calculate
from bot.insurance_planner_gpt.user_info import UserInfo
from common.log import logger

from knowledge_base.knowledge_embedding import BGEQuery


async def fetch(session, url, payload):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Content-Type': 'text/javascript; charset=utf-8',
        'Content-Encoding': 'gzip'
    }
    async with session.get(url, params=payload, headers=headers) as response:
        return await response.text()


def round_up_to_nearest(number):
    try:
        number = float(number)
        number = int(number)
        num_length = len(str(number))

        if num_length == 1:
            target_position = 1
        elif num_length == 2:
            target_position = 10
        elif num_length == 3:
            target_position = 100
        elif num_length == 4:
            target_position = 1000
        elif num_length == 5:
            target_position = 10000
        elif num_length == 6:
            target_position = 100000
        else:
            return number  # 超过六位数的情况，直接返回原值
        return round(number / target_position) * target_position
    except:
        return None


class PremiumCalculation:

    def __init__(self, user_info):
        self.user_info = copy.deepcopy(user_info)
        # 默认男性
        if "sex" not in self.user_info:
            self.user_info["sex"] = "男"
        else:
            if self.user_info["sex"] not in ["男", "女"]:
                self.user_info["sex"] = "男"
        # 默认本人
        if not self.user_info.get('insurance_person'):
            self.user_info["insurance_person"] = "本人"
        # 计算时未收集到年龄 根据保障对象预估出生日期
        self.measure_user_birthday()

    def measure_user_birthday(self):
        measure_age = 30
        try:
            # 本人配偶成人默认30岁
            if self.user_info.get('insurance_person', '') == '本人' \
                    or self.user_info.get('insurance_person', '') == '配偶':
                measure_age = self.user_info.get('current_age', 30)
                if isinstance(measure_age, (int, float)):
                    measure_age = int(measure_age)
                elif isinstance(measure_age, list):
                    measure_age = int(measure_age[0])
                elif isinstance(measure_age, str):
                    pattern = re.compile(r'\d+')
                    measure_age_match = pattern.search(measure_age)
                    if measure_age_match:
                        # 如果找到数字，则将其转换为整数
                        measure_age = int(measure_age_match.group())
                    else:
                        measure_age = 30
            # 父母默认50岁
            elif self.user_info.get('insurance_person', '') == '父母':
                measure_age = self.user_info.get('parents_age', 50)
                if isinstance(measure_age, (int, float)):
                    measure_age = int(measure_age)
                elif isinstance(measure_age, list):
                    measure_age = int(measure_age[0])
                elif isinstance(measure_age, str):
                    pattern = re.compile(r'\d+')
                    measure_age_match = pattern.search(measure_age)
                    if measure_age_match:
                        # 如果找到数字，则将其转换为整数
                        measure_age = int(measure_age_match.group())
                    else:
                        measure_age = 50
            # 孩子默认10岁
            elif self.user_info.get('insurance_person', '') == '孩子':
                measure_age = self.user_info.get('children_age', 10)
                if isinstance(measure_age, (int, float)):
                    measure_age = int(measure_age)
                elif isinstance(measure_age, list):
                    measure_age = int(measure_age[0])
                elif isinstance(measure_age, str):
                    pattern = re.compile(r'\d+')
                    measure_age_match = pattern.search(measure_age)
                    if measure_age_match:
                        # 如果找到数字，则将其转换为整数
                        measure_age = int(measure_age_match.group())
                    else:
                        measure_age = 10
            # 计算出生日期
            if measure_age:
                birth_year = 2024 - measure_age
                birth_date = str(birth_year) + "-01-01"
                self.user_info["birth_date"] = birth_date
        except Exception:
            logger.error("计算出生年月信息异常" + traceback.format_exc())

    knowledge_base_query = BGEQuery()
    knowledge_base_query.load_all_knowledge_base()

    def calculate_life_insurance_coverage(self, cal_type, product_name):
        life_insurance_coverage_remark = "定期寿险的保额=债务（房贷、车贷、欠款）+日常开支（子女致育、赡养老人的费用）。"
        remaining_mortgage_loan_amount = 0
        if ("remaining_mortgage_loan_amount" in self.user_info):
            remaining_mortgage_loan_amount = self.user_info["remaining_mortgage_loan_amount"]
            life_insurance_coverage_remark += f"您的贷款为:{remaining_mortgage_loan_amount}"

        children_cost = self.user_info.get("children_cost", 0)
        if not children_cost:
            children_num = self.user_info.get("children_num", )
            children_age = self.user_info.get("children_age", )
            if children_num or children_age:
                if children_num:
                    if not children_age:
                        children_age = 10
                        life_insurance_coverage_remark += "孩子年龄按照10岁计算。"
                elif not children_num and children_age:
                    if isinstance(children_age, (int, float, str)):
                        children_num = 1
                    elif isinstance(children_age, list):
                        children_num = len(children_age)
                children_future_living = 0
                children_future_education = 0
                if children_num > 1:
                    if len(children_age) == 1:
                        children_age = [children_age] * children_num
                    for age in children_age:
                        if age < 22:
                            children_future_living = children_future_living + (22 - age) * 12000
                            children_future_education = children_future_education + (22 - age) * 30000
                elif children_num == 1:
                    if children_age < 22:
                        children_future_living = (22 - children_age) * 12000
                        children_future_education = (22 - children_age) * 30000
                children_cost = children_future_living + children_future_education
                life_insurance_coverage_remark += "孩子生活费按照12000元/年/人 教育费30000元/年/人 抚养到22岁大学结束, "
                life_insurance_coverage_remark += f"{children_num}个孩子，孩子{children_age}岁,抚养孩子累计{children_cost}元"
        else:
            life_insurance_coverage_remark += f"抚养孩子累计{children_cost}"

        parental_support = self.user_info.get("parents_cost", 0)
        if not parental_support:
            parents_num = self.user_info.get("parents_num", )
            parents_age = self.user_info.get("parents_age", )

            if parents_num or parents_age:
                if parents_num:
                    if not parents_age:
                        parents_age = self.user_info["current_age"] + 30
                elif not parents_num and parents_age:
                    if isinstance(parents_age, (int, float, str)):
                        parents_num = 1
                    elif isinstance(parents_age, list):
                        parents_num = len(parents_age)

                life_insurance_coverage_remark += f"假设赡养的老人年龄为{parents_age}岁,共{parents_num}位老人，"

                parental_support = 0
                if parents_age:
                    if parents_num > 1:
                        for age in parents_age:
                            if age < 85:
                                parental_support = parental_support + (85 - age) * 12000
                    elif parents_num == 1:
                        if parents_age < 85:
                            parental_support = (85 - parents_age) * 12000

                life_insurance_coverage_remark += f"默认赡养到85岁,老人生活费按照12000元/年/人计算,"
                life_insurance_coverage_remark += f"赡养老人累计需要{parental_support}元 "
        else:
            life_insurance_coverage_remark += f"赡养老人累计需要{parental_support}"
        life_insurance_coverage_detail = remaining_mortgage_loan_amount + children_cost + parental_support
        life_insurance_coverage_num = int(life_insurance_coverage_detail / 10000)
        life_insurance_coverage = str(life_insurance_coverage_num) + "万"

        return life_insurance_coverage, life_insurance_coverage_num, life_insurance_coverage_remark

    async def calculate_insurance_coverage(self, need_calculate_insurance_list):
        """{"保额":"","保费":""}"""
        need_calculate_insurance_result_list = []
        try:
            if need_calculate_insurance_list:
                for need_calculate_insurance in need_calculate_insurance_list:
                    calculate_result = {}
                    cal_targets = need_calculate_insurance.get('计算目标', [])
                    cal_type = need_calculate_insurance.get('类型', '')
                    product_details = need_calculate_insurance.get('产品方案', {})
                    if cal_targets:
                        for target in cal_targets:
                            if '保额' in target and product_details:
                                # 计算保额
                                await self.calculate_insurance_coverage_all(cal_type, calculate_result, product_details)
                            elif '保费' in target:
                                # 计算保费
                                await self.calculate_insurance_premium_all(cal_type, calculate_result, product_details)
                    need_calculate_insurance_result_list.append(calculate_result)
        except:
            logger.error(f"处理计算异常，处理内容是{need_calculate_insurance_list},异常是：{traceback.format_exc()}")
        return need_calculate_insurance_result_list

    async def calculate_insurance_premium_all(self, cal_type, calculate_result, product_detail):
        if '保险产品' == cal_type and product_detail:
            product_name = product_detail.get('名称', '').replace("—", "-")
            product_need_item = product_detail.get('产品需求', {})
            if ("重大疾病保险" in product_name or '重疾' in product_name) and '基本保额' not in product_need_item:
                critical_illness_insurance_coverage_num = product_detail.get('保额需求', {}).get('保额(万)')
                if critical_illness_insurance_coverage_num:
                    # 构建查询条件查询向量库
                    if cal_type == '保险产品':
                        search_str = "保险产品:" + product_name + "\n" + "产品属性:基本保额"
                        knowledge_results = self.knowledge_base_query.search_product_item_with_score(search_str,
                                                                                                     top_k=1)
                        product_item_results = [item for item in knowledge_results if '产品属性' in item.metadata]
                        result = product_item_results[0]
                        if '产品属性' in result.metadata:
                            items_val_str = result.metadata.get('属性值', '')
                            if items_val_str:
                                items_val_list = items_val_str.split('/')
                                critical_illness_insurance_coverage_num = self.get_similar_insurance_coverage(
                                    items_val_list,
                                    critical_illness_insurance_coverage_num)
                                product_need_item['基本保额'] = str(critical_illness_insurance_coverage_num) + "万元"

            if ("寿险" in product_name) and '基本保额' not in product_need_item:
                life_insurance_coverage_num = product_detail.get('保额需求', {}).get('保额(万)')
                if life_insurance_coverage_num:
                    # 构建查询条件查询向量库
                    if cal_type == '保险产品':
                        search_str = "保险产品:" + product_name + "\n" + "产品属性:基本保额"
                        knowledge_results = self.knowledge_base_query.search_product_item_with_score(search_str,
                                                                                                     top_k=1)
                        product_item_results = [item for item in knowledge_results if '产品属性' in item.metadata]
                        result = product_item_results[0]
                        if '产品属性' in result.metadata:
                            items_val_str = result.metadata.get('属性值', '')
                            if items_val_str:
                                items_val_list = items_val_str.split('/')
                                life_insurance_coverage_num = self.get_similar_insurance_coverage(
                                    items_val_list, life_insurance_coverage_num)
                                product_need_item['基本保额'] = str(life_insurance_coverage_num) + "万元"
            premium_calculate_result = await premium_calculate(product_name, self.user_info,
                                                               product_need_item)
            if premium_calculate_result:
                premium_calculate_result = round_up_to_nearest(premium_calculate_result)
                product_detail['保费'] = premium_calculate_result
            calculate_result['结果'] = product_detail
        # if '保险产品' == cal_type and product_details:
        #     product_type_premium = {}
        #     for product_detail in product_details:
        #         product_name = product_detail.get('名称', '')
        #         insurance_type = product_detail.get('保险类型', '')
        #         insurance_product_type = product_detail.get('保险产品类型', '')
        #         product_type_premium['保费'] = ""
        #         if '小额医疗' in insurance_product_type:
        #             product_type_premium['名称'] = '百万医疗'
        #             product_type_premium['保费'] = '一般几百'
        #         if '门诊医疗' in insurance_product_type:
        #             product_type_premium['名称'] = '百万医疗'
        #             product_type_premium['保费'] = '一般几百'
        #         if '百万医疗' in insurance_product_type:
        #             product_type_premium['名称'] = '百万医疗'
        #             product_type_premium['保费'] = '一般几百'
        #         if '中端医疗' in insurance_product_type:
        #             product_type_premium['名称'] = '中端医疗'
        #             product_type_premium['保费'] = '一般几百元至几千'
        #         if '高端医疗' in insurance_product_type:
        #             product_type_premium['名称'] = '高端医疗'
        #             product_type_premium['保费'] = '一般几千元至几万'
        #         if '重疾险' in insurance_product_type:
        #             product_type_premium['名称'] = '重疾险'
        #             product_type_premium['保费'] = '一般几千'
        #         if '意外险' in insurance_product_type:
        #             product_type_premium['名称'] = '意外险'
        #             product_type_premium['保费'] = '一般几百'
        #         if '家庭意外险' in insurance_product_type:
        #             product_type_premium['名称'] = '家庭意外险'
        #             product_type_premium['保费'] = '一般几百'
        #         if '境内旅行险' in insurance_product_type:
        #             product_type_premium['名称'] = '境内旅行险'
        #             product_type_premium['保费'] = '一般每天几元或几十'
        #         if '境外旅行险' in insurance_product_type:
        #             product_type_premium['名称'] = '境外旅行险'
        #             product_type_premium['保费'] = '一般每天十几元到几十'
        #         if '定期寿险' in insurance_product_type:
        #             product_type_premium['名称'] = '定期寿险'
        #             product_type_premium['保费'] = '一般在几百元到几千'
        #         product_detail['保费'] = product_type_premium['保费'] if product_type_premium['保费'] else '无'
        elif '保险产品类型' == cal_type and product_detail:
            product_type_premium = {}
            product_type_name = product_detail.get('名称', '')
            product_type_premium['保费'] = ""
            if '小额医疗' in product_type_name:
                product_type_premium['名称'] = '百万医疗'
                product_type_premium['保费'] = '一般几百'
            if '门诊医疗' in product_type_name:
                product_type_premium['名称'] = '百万医疗'
                product_type_premium['保费'] = '一般几百'
            if '百万医疗' in product_type_name:
                product_type_premium['名称'] = '百万医疗'
                product_type_premium['保费'] = '一般几百'
            if '中端医疗' in product_type_name:
                product_type_premium['名称'] = '中端医疗'
                product_type_premium['保费'] = '一般几百元至几千'
            if '高端医疗' in product_type_name:
                product_type_premium['名称'] = '高端医疗'
                product_type_premium['保费'] = '一般几千元至几万'
            if '重疾险' in product_type_name:
                product_type_premium['名称'] = '重疾险'
                product_type_premium['保费'] = '一般几千'
            if '意外险' in product_type_name:
                product_type_premium['名称'] = '意外险'
                product_type_premium['保费'] = '一般几百'
            if '家庭意外险' in product_type_name:
                product_type_premium['名称'] = '家庭意外险'
                product_type_premium['保费'] = '一般几百'
            if '境内旅行险' in product_type_name:
                product_type_premium['名称'] = '境内旅行险'
                product_type_premium['保费'] = '一般每天几元或几十'
            if '境外旅行险' in product_type_name:
                product_type_premium['名称'] = '境外旅行险'
                product_type_premium['保费'] = '一般每天十几元到几十'
            if '定期寿险' in product_type_name:
                product_type_premium['名称'] = '定期寿险'
                product_type_premium['保费'] = '一般在几百元到几千'
            product_detail['保费'] = product_type_premium['保费'] if product_type_premium['保费'] else '无'
        elif '保险类型' == cal_type and product_detail:
            insurance_type_premium = {}
            insurance_type_name = product_detail.get('名称', {})
            insurance_type_premium['保费'] = ""
            if '医疗险' in insurance_type_name:
                insurance_type_premium['名称'] = '医疗险'
                insurance_type_premium['保费'] = '一般几百元到几千'
            if '重疾险' in insurance_type_name:
                insurance_type_premium['名称'] = '重疾险'
                insurance_type_premium['保费'] = '一般几千'
            if '意外险' in insurance_type_name:
                insurance_type_premium['名称'] = '意外险'
                insurance_type_premium['保费'] = '一般几百'
            if '旅意险' in insurance_type_name:
                insurance_type_premium['名称'] = '旅意险'
                insurance_type_premium['保费'] = '一般几元十几'
            if '定期寿险' in insurance_type_name:
                insurance_type_premium['名称'] = '定期寿险'
                insurance_type_premium['保费'] = '一般在几百元到几千'
            product_detail['保费'] = insurance_type_premium['保费'] if insurance_type_premium['保费'] else '无'

    async def calculate_insurance_coverage_all(self, cal_type, calculate_result, product_detail):
        name = product_detail.get('名称', '')
        insurance_type = product_detail.get('保险类型', '')
        insurance_product_type = product_detail.get('保险产品类型', '')
        if '医疗' in name or '医疗险' in insurance_type:
            insurance_coverage_medical = {}
            medical_insurance_coverage, medical_insurance_coverage_num, medical_insurance_coverage_remark = self.calculate_medical_insurance_coverage(
                cal_type, name)
            insurance_coverage_medical['保额说明'] = medical_insurance_coverage_remark
            insurance_coverage_medical['保额(万)'] = medical_insurance_coverage_num
            insurance_coverage_medical['保额范围'] = medical_insurance_coverage
            product_detail['保额需求'] = insurance_coverage_medical
        if '重疾险' in name or '重大疾病保险' in name or '重疾险' in insurance_type:
            insurance_coverage_critical_illness = {}
            critical_illness_insurance_coverage, critical_illness_insurance_coverage_num, \
            critical_illness_insurance_coverage_remark = self.calculate_critical_illness_insurance_coverage(
                cal_type, name)
            insurance_coverage_critical_illness[
                '保额说明'] = critical_illness_insurance_coverage_remark
            insurance_coverage_critical_illness[
                '保额(万)'] = critical_illness_insurance_coverage_num
            insurance_coverage_critical_illness[
                '保额范围'] = critical_illness_insurance_coverage
            product_detail['保额需求'] = insurance_coverage_critical_illness
        if '意外' in name or '意外' in insurance_type:
            insurance_coverage_accident = {}
            accident_insurance_coverage, accident_insurance_coverage_num, accident_insurance_coverage_remark = self.calculate_accident_insurance_coverage(
                cal_type, name)
            insurance_coverage_accident['保额说明'] = accident_insurance_coverage_remark
            insurance_coverage_accident['保额(万)'] = accident_insurance_coverage_num
            insurance_coverage_accident['保额范围'] = accident_insurance_coverage
            product_detail['保额需求'] = insurance_coverage_accident
        if '旅游' in name or '旅行' in name or '旅意' in name or '旅意' in insurance_type:
            insurance_coverage_travel_accident = {}
            travel_accident_insurance_coverage, travel_accident_insurance_coverage_num, travel_accident_insurance_coverage_remark = \
                self.calculate_travel_accident_insurance_coverage(cal_type)
            insurance_coverage_travel_accident['保额说明'] = travel_accident_insurance_coverage_remark
            insurance_coverage_travel_accident['保额(万)'] = travel_accident_insurance_coverage_num
            insurance_coverage_travel_accident['保额范围'] = travel_accident_insurance_coverage
            product_detail['保额需求'] = insurance_coverage_travel_accident

            product_detail['保额需求'] = insurance_coverage_travel_accident
        if '定期寿险' in name or '定期寿险' in insurance_type:
            insurance_coverage_life = {}
            life_insurance_coverage, life_insurance_coverage_num, life_insurance_coverage_remark = self.calculate_life_insurance_coverage(
                cal_type, name)
            insurance_coverage_life['保额说明'] = life_insurance_coverage_remark
            insurance_coverage_life['保额(万)'] = life_insurance_coverage_num
            insurance_coverage_life['保额范围'] = life_insurance_coverage
            product_detail['保额需求'] = insurance_coverage_life
        calculate_result['结果'] = product_detail

    def calculate_medical_insurance_coverage(self, cal_type, product_name):
        medical_insurance_coverage = ""
        medical_insurance_coverage_remark = ""
        medical_insurance_coverage_num = None

        if cal_type == "保险类型":
            medical_insurance_coverage_num = 10
            medical_insurance_coverage = "10万以上"
            medical_insurance_coverage_remark = "医疗险保额一般选择10万以上，满足看病治疗的费用。"

        if cal_type == "保险产品类型":
            if product_name == "小额医疗险":
                medical_insurance_coverage_num = 10
                medical_insurance_coverage = "10万以内"
                medical_insurance_coverage_remark = "小额医疗险保额一般选择10万以内，这类保险可以覆盖普通小病住院、意外住院医疗、自费药、门诊费用等医疗支出。"

            if product_name == "门诊医疗险":
                medical_insurance_coverage_num = 1
                medical_insurance_coverage = "1万以内"
                medical_insurance_coverage_remark = "门诊险保额一般选择1万以内，专门用于报销被保险人在门诊治疗期间产生的医疗费用"

            if product_name == "百万医疗险":
                medical_insurance_coverage_num = 100
                medical_insurance_coverage = "100万以上"
                medical_insurance_coverage_remark = "百万医疗险保额一般选择100万以上，可以覆盖大部分医疗费用，为被保险人提供高额度的医疗保障。"

        return medical_insurance_coverage, medical_insurance_coverage_num, \
               medical_insurance_coverage_remark

    def calculate_travel_accident_insurance_coverage(self, cal_type):
        travel_accident_insurance_coverage = ""
        travel_accident_insurance_coverage_remark = ""
        travel_accident_insurance_coverage_num = None

        if cal_type != "保险产品":
            travel_accident_insurance_coverage_remark = '旅意险需要考虑意外医疗保障，交通安全保障，个人责任保障等，一般建议最少10万元'
            travel_accident_insurance_coverage_num = 10
            travel_accident_insurance_coverage = '10万'

        return travel_accident_insurance_coverage, travel_accident_insurance_coverage_num, \
               travel_accident_insurance_coverage_remark

    def calculate_critical_illness_insurance_coverage(self, cal_type, product_name):
        critical_illness_insurance_coverage = ""
        critical_illness_insurance_coverage_remark = ""
        critical_illness_insurance_coverage_num = ""

        insurance_person = self.user_info.get('insurance_person', '本人')
        if insurance_person:
            measure_life_phases = ""
            if insurance_person == '本人' or insurance_person == '配偶':
                measure_life_phases = self.user_info.get('life_phases', '')
            elif insurance_person == '父母':
                measure_life_phases = self.user_info.get('parents_life_phases', '')
            elif insurance_person == '孩子':
                measure_life_phases = self.user_info.get('children_life_phases', '')

            if (
                    insurance_person == '本人' or insurance_person == '配偶') and measure_life_phases and measure_life_phases == '退休期':
                critical_illness_insurance_coverage_num = 30
                critical_illness_insurance_coverage = "30 - 40万（重大疾病的平均治疗费用）"
                critical_illness_insurance_coverage_remark = "退休后重大疾病保险需要弥补患大病的经济损失，保额建议最少30万,覆盖平均重疾的治疗费用。"
            elif insurance_person == '父母':
                critical_illness_insurance_coverage_num = 30
                critical_illness_insurance_coverage = "30 - 40万（重大疾病的平均治疗费用）"
                critical_illness_insurance_coverage_remark = "给父母配置重大疾病保险可以弥补患大病给家庭带来的经济损失，保额建议最少30万,覆盖平均重疾的治疗费用。"
            elif (
                    insurance_person == '本人' or insurance_person == '配偶') and (
                    "family_annual_expenditure" in self.user_info and isinstance(
                self.user_info["family_annual_expenditure"],
                (int, float))) and self.user_info[
                "family_annual_expenditure"] > 0:
                critical_illness_insurance_coverage_tuple = (
                    math.ceil(3 * self.user_info["family_annual_expenditure"] / 10000),
                    math.ceil(5 * self.user_info["family_annual_expenditure"] / 10000))
                critical_illness_insurance_coverage = str(critical_illness_insurance_coverage_tuple[0]) + "万-" + str(
                    critical_illness_insurance_coverage_tuple[1]) + "万"
                critical_illness_insurance_coverage_num = critical_illness_insurance_coverage_tuple[0]
                critical_illness_insurance_coverage_remark = f'发生重大疾病，身体比较虚弱需要配合治疗，治疗加上康复期间至少需要3-5年，所以重疾险保额一般为家庭支出的3-5倍 ' \
                                                             f'根据您的实际情况保额范围是:{critical_illness_insurance_coverage}。'
            elif insurance_person == '孩子':
                critical_illness_insurance_coverage_remark = f'儿童重疾对家庭的医疗支出影响非常大，而且还有可能父母中有一方会辞去工作全职照看。给宝宝配置重大疾病的保额应该是家庭年支出的5倍。' \
                                                             f'根据您的实际情况保额范围是:{critical_illness_insurance_coverage}。'
            elif insurance_person == '孩子' and (
                    "family_annual_expenditure" in self.user_info and isinstance(
                self.user_info["family_annual_expenditure"],
                (int, float))) and self.user_info["family_annual_expenditure"] > 0:
                critical_illness_insurance_coverage_num = math.ceil(
                    5 * self.user_info["family_annual_expenditure"] / 10000)
                critical_illness_insurance_coverage = str(critical_illness_insurance_coverage_num) + "万"
                critical_illness_insurance_coverage_remark = f'儿童重疾对家庭的医疗支出影响非常大，而且还有可能父母中有一方会辞去工作全职照看。给宝宝配置重大疾病的保额应该是家庭年支出的5倍。' \
                                                             f'根据您的实际情况保额范围是:{critical_illness_insurance_coverage}。'
        return critical_illness_insurance_coverage, critical_illness_insurance_coverage_num, critical_illness_insurance_coverage_remark

    def extract_amount(self, string):
        # 从字符串中提取数字部分
        amount_str = ''.join(filter(str.isdigit, string))
        return int(amount_str) if amount_str else 0

    def get_similar_insurance_coverage(self, items_val_list, critical_illness_insurance_coverage_num):
        # 过滤大于目标数字的数字，并找到最小值
        filtered_numbers = [self.extract_amount(num) for num in items_val_list if
                            self.extract_amount(num) > critical_illness_insurance_coverage_num]
        # 如果存在大于目标的数字，则返回最小值；否则返回None
        if filtered_numbers:
            # 如果存在大于目标的金额，则返回最小值
            return min(filtered_numbers)
        else:
            # 如果不存在大于目标的金额，则返回数组中的最大值
            return max([self.extract_amount(amount) for amount in items_val_list])

    def calculate_accident_insurance_coverage(self, cal_type, name):
        accident_insurance_coverage = ""
        accident_insurance_coverage_num = ""
        accident_insurance_coverage_remark = ""

        if cal_type == "保险类型":
            # 保障对象的人生阶段
            measure_life_phases = ""
            insurance_person = self.user_info.get('insurance_person', '本人')
            if insurance_person:
                if insurance_person == '本人' or insurance_person == '配偶':
                    measure_life_phases = self.user_info.get('life_phases', '')
                elif insurance_person == '父母':
                    measure_life_phases = self.user_info.get('parents_life_phases', '')
                elif insurance_person == '孩子':
                    measure_life_phases = self.user_info.get('children_life_phases', '')
                # 保额计算
                if (
                        insurance_person == '本人' or insurance_person == '配偶') and measure_life_phases and measure_life_phases in "退休期":
                    accident_insurance_coverage_num = 30
                    accident_insurance_coverage = "医疗保额2万左右，身故保额30-50万"
                    accident_insurance_coverage_remark = "年龄大容易发生磕碰、骨折等意外状况。意外险身故保障的保额应该考虑30-50万左右，意外医疗的保额最好是2万左右，保障意外门诊的花销。"
                elif (insurance_person == '本人' or insurance_person == '配偶') and (
                        "family_annual_expenditure" in self.user_info and isinstance(
                    self.user_info["family_annual_expenditure"],
                    (int, float))) and self.user_info[
                    "family_annual_expenditure"] > 0:
                    accident_insurance_num_tuple = (
                        math.ceil(5 * self.user_info["family_annual_expenditure"] / 10000),
                        math.ceil(10 * self.user_info["family_annual_expenditure"] / 10000))
                    accident_insurance_coverage = str(accident_insurance_num_tuple[0]) + "万-" + str(
                        accident_insurance_num_tuple[1]) + "万"
                    accident_insurance_coverage_num = accident_insurance_num_tuple[0]
                    accident_insurance_coverage_remark = "成年人意外险保额一般为5-10倍年支出"
                elif insurance_person == '孩子' and measure_life_phases:
                    if measure_life_phases in "低龄儿童" or measure_life_phases in '大龄儿童':
                        accident_insurance_coverage_num = 20
                        accident_insurance_coverage = "身故保额不超过20万"
                        accident_insurance_coverage_remark = "监管规定，为了防止道德风险，限制了未成年人的身故赔付限额：0-9周岁不超过20万"
                    elif measure_life_phases in "低龄青少年" or measure_life_phases in "大龄青少年":
                        accident_insurance_coverage_num = 50
                        accident_insurance_coverage = "保额不超过50万"
                        accident_insurance_coverage_remark = "监管规定，为了防止道德风险，限制了未成年人的身故赔付限额:10-17周岁不超过50万"
                elif insurance_person == '父母':
                    accident_insurance_coverage_num = 30
                    accident_insurance_coverage = "意外身故保额30-50万，意外医疗的保额是2万"
                    accident_insurance_coverage_remark = "父母年龄大容易发生磕碰、骨折等意外状况。意外险身故保障的保额应该考虑30-50万左右意外身故保额30-50万，意外医疗的保额是2万"

        if cal_type == "保险产品类型":
            # if name == "意外险":
            # 保障对象的人生阶段
            measure_life_phases = ""
            insurance_person = self.user_info.get('insurance_person', '本人')
            if insurance_person:
                if insurance_person == '本人' or insurance_person == '配偶':
                    measure_life_phases = self.user_info.get('life_phases', '')
                elif insurance_person == '父母':
                    measure_life_phases = self.user_info.get('parents_life_phases', '')
                elif insurance_person == '孩子':
                    measure_life_phases = self.user_info.get('children_life_phases', '')
                # 保额计算
                if (
                        insurance_person == '本人' or insurance_person == '配偶') and measure_life_phases and measure_life_phases in "退休期":
                    accident_insurance_coverage_num = 30
                    accident_insurance_coverage = "医疗保额2万左右，身故保额30-50万"
                    accident_insurance_coverage_remark = "年龄大容易发生磕碰、骨折等意外状况。意外险身故保障的保额应该考虑30-50万左右，意外医疗的保额最好是2万左右，保障意外门诊的花销。"
                elif (insurance_person == '本人' or insurance_person == '配偶') and (
                        "family_annual_expenditure" in self.user_info and isinstance(
                    self.user_info["family_annual_expenditure"],
                    (int, float))) and self.user_info[
                    "family_annual_expenditure"] > 0:
                    accident_insurance_num_tuple = (
                        math.ceil(5 * self.user_info["family_annual_expenditure"] / 10000),
                        math.ceil(10 * self.user_info["family_annual_expenditure"] / 10000))
                    accident_insurance_coverage = str(accident_insurance_num_tuple[0]) + "万-" + str(
                        accident_insurance_num_tuple[1]) + "万"
                    accident_insurance_coverage_num = accident_insurance_num_tuple[0]
                    accident_insurance_coverage_remark = "成年人意外险保额一般为5-10倍年支出"
                elif insurance_person == '孩子' and measure_life_phases:
                    if measure_life_phases in "低龄儿童" or measure_life_phases in '大龄儿童':
                        accident_insurance_coverage_num = 20
                        accident_insurance_coverage = "身故保额不超过20万"
                        accident_insurance_coverage_remark = "监管规定，为了防止道德风险，限制了未成年人的身故赔付限额：0-9周岁不超过20万"
                    elif measure_life_phases in "低龄青少年" or measure_life_phases in "大龄青少年":
                        accident_insurance_coverage_num = 50
                        accident_insurance_coverage = "保额不超过50万"
                        accident_insurance_coverage_remark = "监管规定，为了防止道德风险，限制了未成年人的身故赔付限额:10-17周岁不超过50万"
                elif insurance_person == '父母':
                    accident_insurance_coverage_num = 30
                    accident_insurance_coverage = "意外身故保额30-50万，意外医疗的保额是2万"
                    accident_insurance_coverage_remark = "父母年龄大容易发生磕碰、骨折等意外状况。意外险身故保障的保额应该考虑30-50万左右意外身故保额30-50万，意外医疗的保额是2万"
            # if name == "家庭意外险":
            #     accident_insurance_coverage_num = 1
            #     accident_insurance_coverage = "1万以上"
            #     accident_insurance_coverage_remark = "小额医疗险保额一般选择1万以上"

        return accident_insurance_coverage, accident_insurance_coverage_num, accident_insurance_coverage_remark

    async def transfer_product2str(self, insurance_coverage_solutions):
        solution_str = ""
        try:
            if insurance_coverage_solutions:
                for insurance_coverage_solution in insurance_coverage_solutions:
                    product_detail = insurance_coverage_solution.get('结果', '')
                    if product_detail:
                        product_name = product_detail.get('名称', '')
                        insurance_fee = product_detail.get('保费', '')
                        product_need_info = product_detail.get('产品需求', '')
                        insurance_coverage_remark = product_detail.get('保额需求', {}).get('保额说明', {})
                        insurance_coverage = product_detail.get('保额需求', {}).get('保额(万)', {})
                        product_need_info_str = ""
                        # 没有保额先不算保费
                        product_insurance_coverage = ''
                        if insurance_coverage != 0:
                            solution_str += f"{product_name},"
                            if product_need_info:
                                product_insurance_coverage = product_need_info.get('基本保额', '')
                            if insurance_fee:
                                if product_insurance_coverage:
                                    solution_str += f" 产品保额：{product_insurance_coverage}。"
                                if insurance_coverage_remark:
                                    solution_str += f"{insurance_coverage_remark},"
                                solution_str += f"保费大概{insurance_fee} 元\n"
        except:
            logger.error(f"生成保费计算话术异常,处理内容是：{insurance_coverage_solutions}，异常是：{traceback.format_exc()}")
        return solution_str


if __name__ == '__main__':
    # user_info = {'current_age': 30, 'insurance_person': '本人', 'family_annual_income': 200000,
    #              'family_annual_expenditure': 100000, "parents_num": 2, "parents_age": [50, 52], "children_age": 10}

    user_info_cn = {'本人性别': '男', '是否已结婚': '否', '当前年收入': 100000, '当前年支出': 50000, '本人年龄': 20, '人生阶段': '入职期',
                    '年保费预算': 1000, '被保人': '父母', '孩子年龄': 10, '父母年龄': '50岁'}
    # user_info_cn = {}

    user_info = UserInfo.get_english_dict(user_info_cn)
    premium_calculation = PremiumCalculation(user_info)
    premium_calculation.measure_user_birthday()

    # premium = asyncio.run(
    #     premium_calculation.calculate_insurance_coverage([{'类型': '保险产品',
    #                                                        '产品方案':
    #                                                            {'名称': '守卫者6号重大疾病保险-保终身（A款）',
    #                                                             '产品需求': {}},
    #                                                        '计算目标': ['计算保额', '计算保费']}]))
    # premium = asyncio.run(
    #     premium_calculation.calculate_insurance_coverage(
    #         {'类型': '保险类型', '产品方案': [{'名称': '百万医疗'}, {'名称': '重疾险'}, {'名称': '意外险'}, {'名称': '定期寿险'}, {'名称': '旅意险'}],
    #          '计算目标': ['计算保额', '计算保费']}))
    # premium = asyncio.run(
    #     premium_calculation.calculate_insurance_coverage(
    #         {'类型': '保险产品', '产品方案': [{'名称': '慧择铁甲小保2号少儿长期医疗险-计划二', '产品需求': {'住院医疗保险': '含'}}], '计算目标': ['计算保额', '计算保费']}))
    # print(premium)
    # print(asyncio.run(premium_calculation.transfer_product2str(premium)))

    # loop.run_until_complete(premium_calculation.total_premium())
    # loop.run_until_complete(premium_calculation.medical_insurance_premium())
    # loop.run_until_complete(premium_calculation.accident_insurance_premium())
    # loop.run_until_complete(premium_calculation.life_insurance_premium())
    # print(round_up_to_nearest(32))
